﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright company="Microsoft Corp." file="SubmitJobCommand.cs">
//   All rights reserved. See License.txt in the project root for license information.
// </copyright>
// 
// --------------------------------------------------------------------------------------------------------------------
namespace HpcSchedulerManagement.Commands
{
    using System;
    using System.Net;

    using Common;

    using HpcSchedulerManagement.DataContracts;

    using Microsoft.Hpc.Scheduler.Properties;

    using RestClient;

    public class SubmitJobCommand : HpcSchedulerCommandBase
    {
        private readonly string hpcClusterName;

        private readonly int jobId;

        private readonly SchedulerJob job;

        private readonly NetworkCredential credential;

        public SubmitJobCommand(IHpcSchedulerServiceContext serviceContext, string hpcClusterName, int jobId, SchedulerJob job, NetworkCredential credential)
            : base(serviceContext)
        {
            if (string.IsNullOrEmpty(hpcClusterName))
            {
                throw new ArgumentException("Hpc cluster name must not be null or empty.", "hpcClusterName");
            }

            if (jobId <= 0)
            {
                throw new ArgumentException("Job id must not be less or equal to 0.", "jobId");
            }

            if (job == null)
            {
                throw new ArgumentNullException("job", "Job must not be null.");
            }

            this.hpcClusterName = hpcClusterName;
            this.jobId = jobId;
            this.job = job;
            this.credential = credential;
        }

        protected override RequestContext GetRequestContext()
        {
            return this.CreatePostOperationRequestContext();
        }

        protected override string FormatPath(IHpcSchedulerServiceContext serviceContext)
        {
            return string.Format("{0}/Job/{1}/Submit", this.hpcClusterName, this.jobId);
        }

        protected override string FormatBody()
        {
            var properties = HpcDataContractsTranslator.JobToArrayOfProperties(this.job);
            if (string.IsNullOrEmpty(this.job.UserName) && this.credential != null)
            {
                properties.Property.Add(new Property(JobPropertyIds.UserName, this.credential.UserName));
            }

            if (string.IsNullOrEmpty(this.job.Password) && this.credential != null)
            {
                properties.Property.Add(new Property(JobPropertyIds.EncryptedPassword, this.credential.Password));
            }

            return XmlHelper.Serialize(properties);
        }
    }
}